import json
import os

class FileStorage:
    def __init__(self, filename):
        self.filename = os.path.join(os.path.dirname(__file__), '..', 'data', filename)
        os.makedirs(os.path.dirname(self.filename), exist_ok=True)
        if not os.path.exists(self.filename):
            with open(self.filename, 'w', encoding='utf-8') as f:
                json.dump([], f)

    def read(self):
        with open(self.filename, 'r', encoding='utf-8') as f:
            return json.load(f)

    def write(self, data):
        with open(self.filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def find_one(self, key, value):
        data = self.read()
        return next((item for item in data if item[key] == value), None)

    def find_many(self, key, value):
        data = self.read()
        return [item for item in data if item[key] == value]

    def insert(self, item):
        data = self.read()
        data.append(item)
        self.write(data)
        return item

    def update(self, key, value, new_data):
        data = self.read()
        for item in data:
            if item[key] == value:
                item.update(new_data)
                self.write(data)
                return item
        return None